package com.qzuser.sendmessagebasic.common.tool;

import com.qzuser.sendmessagebasic.common.exception.ToolException;

import java.io.*;

public class BinaryTool {
    public static byte[] toByteArray(Object obj) throws ToolException {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
                objectOutputStream.writeObject(obj);
            }
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new ToolException("[BinaryTool] 序列化为字节数组失败");
        }
    }

    public static Object fromByteArray(byte[] bytes) throws ToolException {
        Object obj = null;
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
            try (ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
                obj = objectInputStream.readObject();
            }
            return obj;
        } catch (Exception e) {
            throw new ToolException("[BinaryTool] 字节数组序列化为对象失败");
        }
    }
}
